﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GM.Model.SubSonic;

namespace GM.Forms
{
    public partial class LoginForm : Form
    {
        private bool m_isLoginValid;
        private bool m_isPasswordValid;

        public LoginForm()
        {
            InitializeComponent();
        }

        private void gbtnCancel_Click(object sender, EventArgs e)
        {
            Hide();
            if (LoginCancelled != null)
                LoginCancelled();
        }

        private void gbtnLogin_Click(object sender, EventArgs e)
        {
            if (!(m_isLoginValid && m_isPasswordValid))
                return;

            backgroundWorker.RunWorkerAsync(new object[] {tbxLogin.Text, tbxPassword.Text});
        }

        private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            Hide();
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var data = e.Argument as object[];
            SetProgress(true);
            var login = Pracownik.Find(x => x.login == (string) data[0] && x.haslo == (string) data[1]);
            SetProgress(false);
            if (login.Count > 0 && LoginRequested != null)
                LoginRequested();
            Invoke((MethodInvoker) Hide);
        }

        private void tbxLogin_Validated(object sender, EventArgs e)
        {
            var login = tbxLogin.Text.Trim();
            if (string.IsNullOrEmpty(login))
            {
                errorProvider.SetError(tbxLogin, "Login nie może być pusty.");
                m_isLoginValid = false;
            }
            else
            {
                errorProvider.SetError(tbxLogin, string.Empty);
                m_isLoginValid = true;
            }
        }

        private void tbxPassword_Validated(object sender, EventArgs e)
        {
            var password = tbxPassword.Text.Trim();
            if (string.IsNullOrEmpty(password))
            {
                errorProvider.SetError(tbxPassword, "Hasło nie może być puste.");
                m_isPasswordValid = false;
            }
            else
            {
                errorProvider.SetError(tbxLogin, string.Empty);
                m_isPasswordValid = true;
            }
        }

        private void SetProgress(bool visible)
        {
            if (progressBar.InvokeRequired)
                progressBar.BeginInvoke((MethodInvoker)delegate { progressBar.Visible = visible; });
            else
                progressBar.Visible = visible;
        }

        public event Action LoginRequested;

        public event Action LoginCancelled;
    }
}
